<template>
  <div class="operation-log-container">
    <div class="header">
      <h2>操作日志</h2>
      <div class="filter-section">
        <el-input
          v-model="filterParams.username"
          placeholder="搜索操作人"
          class="filter-input"
          clearable
          @clear="handleFilter"
          @keyup.enter="handleFilter"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-select
          v-model="filterParams.action"
          placeholder="选择模块"
          class="filter-select"
          clearable
          @change="handleFilter"
        >
          <el-option
            v-for="item in actionOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        />
        
        <el-button type="primary" @click="handleFilter">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        
        <el-button @click="handleReset">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
        
        <el-button type="warning" style="display: none;" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </div>
    </div>

    <div class="table-container">
      <el-table
        :data="logList"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column
          prop="id"
          label="ID"
          width="80"
          align="center"
        />
        <el-table-column
          prop="action"
          label="操作模块"
          width="150"
          align="center"
        />
        <el-table-column
          prop="content"
          label="操作内容"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column
          prop="username"
          label="操作人"
          width="120"
          align="center"
        />
        <el-table-column
          prop="geoip"
          label="操作IP"
          width="140"
          align="center"
        >
          <template #default="{ row }">
            <el-tag v-if="row.geoip" type="info">{{ row.geoip }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="create_at"
          label="创建时间"
          width="180"
          align="center"
        >
          <template #default="{ row }">
            {{ formatDateTime(row.create_at) }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="120"
          align="center"
          fixed="right"
        >
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              @click="handleViewDetail(row)"
            >
              详情
            </el-button>
            <el-button style="display: none;"
              type="danger"
              link
              @click="handleDelete(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 日志详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="操作日志详情"
      width="600px"
    >
      <el-descriptions :column="1" border v-if="currentLog">
        <el-descriptions-item label="ID">
          {{ currentLog.id }}
        </el-descriptions-item>
        <el-descriptions-item label="操作模块">
          {{ currentLog.action }}
        </el-descriptions-item>
        <el-descriptions-item label="操作内容">
          {{ currentLog.content }}
        </el-descriptions-item>
        <el-descriptions-item label="操作人">
          {{ currentLog.username }}
        </el-descriptions-item>
        <el-descriptions-item label="操作IP">
          <el-tag v-if="currentLog.geoip" type="info">{{ currentLog.geoip }}</el-tag>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDateTime(currentLog.create_at) }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Download } from '@element-plus/icons-vue'
import type { OperationLog, FilterParams, Pagination } from '@/types/log'
import { 
  getLogList, 
  deleteLog, 
  exportLog,
  getActionOptions 
} from '@/api/operationLog'

// 响应式数据
const logList = ref<OperationLog[]>([])
const loading = ref(false)
const detailDialogVisible = ref(false)
const currentLog = ref<OperationLog | null>(null)
const dateRange = ref<string[]>([])

// 筛选参数
const filterParams = reactive<FilterParams>({
  username: '',
  action: ''
})

// 分页参数
const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 操作模块选项
const actionOptions = ref<{label: string, value: string}[]>([])

// 方法
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return dateTime.replace('T', ' ').substring(0, 19)
}

const fetchLogList = async () => {
  loading.value = true
  try {
    const params: Record<string, any> = {
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      ...filterParams
    }

    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await getLogList(params)

    if (response.code === 200) {
      logList.value = response.data.list
      pagination.total = response.data.total
      pagination.currentPage = response.data.current_page
      pagination.pageSize = response.data.page_size
    } else {
      ElMessage.error(response.message || '获取日志列表失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试')
    console.error('Error fetching logs:', error)
  } finally {
    loading.value = false
  }
}

const fetchActionOptions = async () => {
  try {
    const response = await getActionOptions()
    if (response.code === 200) {
      actionOptions.value = response.data.map((item: string) => ({
        label: item,
        value: item
      }))
    }
  } catch (error) {
    console.error('Error fetching action options:', error)
  }
}

const handleFilter = () => {
  pagination.currentPage = 1
  fetchLogList()
}

const handleReset = () => {
  filterParams.username = ''
  filterParams.action = ''
  filterParams.start_date = ''
  filterParams.end_date = ''
  dateRange.value = []
  pagination.currentPage = 1
  fetchLogList()
}

const handleDateChange = (dates: string[]) => {
  if (dates && dates.length === 2) {
    filterParams.start_date = dates[0]
    filterParams.end_date = dates[1]
  } else {
    filterParams.start_date = ''
    filterParams.end_date = ''
  }
  handleFilter()
}

const handleSizeChange = (newSize: number) => {
  pagination.pageSize = newSize
  fetchLogList()
}

const handleCurrentChange = (newPage: number) => {
  pagination.currentPage = newPage
  fetchLogList()
}

const handleViewDetail = (log: OperationLog) => {
  currentLog.value = log
  detailDialogVisible.value = true
}

const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这条日志吗？', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    
    const response = await deleteLog(id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchLogList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    // 用户取消删除
    if (error === 'cancel') {
      return
    }
    ElMessage.error('删除失败')
  }
}

const handleExport = async () => {
  try {
    loading.value = true
    const params: Record<string, any> = { ...filterParams }

    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await exportLog(params)

    if (response instanceof Blob) {
      // 创建下载链接
      const url = window.URL.createObjectURL(response)
      const link = document.createElement('a')
      link.href = url
      link.download = `操作日志_${new Date().getTime()}.xlsx`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      ElMessage.success('导出成功')
    } else {
      ElMessage.error('导出失败')
    }
  } catch (error) {
    ElMessage.error('导出失败')
    console.error('Export error:', error)
  } finally {
    loading.value = false
  }
}

// 生命周期
onMounted(() => {
  fetchLogList()
  fetchActionOptions()
})
</script>

<style scoped>
.operation-log-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header h2 {
  margin: 0 0 20px 0;
  color: #303133;
}

.filter-section {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-input {
  width: 200px;
}

.filter-select {
  width: 150px;
}

.table-container {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

:deep(.el-table .cell) {
  padding: 8px 12px;
}

:deep(.el-descriptions__label) {
  width: 100px;
  font-weight: 600;
}
</style>